package com.zf.shuashua.ui.custom;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.duoyou.task.openapi.DyAdApi;
import com.mediamain.android.nativead.Ad;
import com.mediamain.android.nativead.AdCallBack;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.tencent.bugly.beta.Beta;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.InteractionAdListener;
import com.zf.shuashua.advert.NativeAdvertManager;
import com.zf.shuashua.advert.OnRewardListener;
import com.zf.shuashua.advert.RewardAdvertManager;
import com.zf.shuashua.advert.TTAdManagerHolder;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseFragment;
import com.zf.shuashua.bean.BindWX;
import com.zf.shuashua.bean.Giftjson;
import com.zf.shuashua.bean.JumpJson;
import com.zf.shuashua.bean.NationalBean;
import com.zf.shuashua.bean.ScrollModle;
import com.zf.shuashua.bean.ToShare;
import com.zf.shuashua.helper.LoadDialogManager;
import com.zf.shuashua.helper.MarketTools;
import com.zf.shuashua.manager.CalendarManager;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.ui.popup.RewardPopupFragment;
import com.zf.shuashua.utils.CommonConstants;
import com.zf.shuashua.utils.NotificationUtil;
import com.zf.shuashua.utils.ToNotification;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.utils.Util;
import com.zf.shuashua.utils.WebUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;

import static com.umeng.socialize.utils.ContextUtil.getPackageName;

public class H5Fragment2 extends BaseFragment {

    private WebView webview;
    private String url;
    private Disposable disposable;
    public static final int REFRESH = 5;//刷新
    public static final int WITHDRAW = 8;//提现
    public boolean isFromReward = false;
    private boolean toNotify = false;//去设置通知开关

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    private Ad ad;
    private TTAdNative mTTAdNative;
    private TTNativeExpressAd mTTAd;

    public H5Fragment2() {
        super();
    }

    private String mAdvertType = AdvertConstants.REWARD_TYPE_TASK;
    private TextView mTvTitle;
    private String type = "";
    private String type1 = "";
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            String open_id = data.get("uid");
            if (open_id == null) {
                open_id = "";
            }
            String nick_name = data.get("name");
            if (nick_name == null) {
                nick_name = "";
            }
            String avatar = data.get("iconurl");
            if (avatar == null) {
                avatar = "";
            }
            String sex = data.get("gender");
            if (sex == null) {
                sex = "";
            }
            String city = data.get("city");
            if (city == null) {
                city = "";
            }

            if (SHARE_MEDIA.QQ == platform) {
                type = "qq";
                type1 = AdvertConstants.REWARD_TYPE_BIND_QQ;
            } else if (SHARE_MEDIA.SINA == platform) {
                type = "weibo";
                type1 = AdvertConstants.REWARD_TYPE_BIND_WEIBO;
            } else if (SHARE_MEDIA.WEIXIN == platform) {
                type = "wechat";
                type1 = AdvertConstants.REWARD_TYPE_BIND;
                open_id = data.get("openid");
                if (open_id == null) {
                    open_id = "";
                }
            }


            HttpData.getInstance().bindThird(type, open_id, nick_name, avatar, sex, city, "", "", "", "", new ACallback<BindWX>() {
                @Override
                public void onSuccess(BindWX data) {
                    LoadDialogManager.getInstance().dismiss();
                    if (data != null) {
                        if (data.isStatus()) {
                            ToastUtil.show(mActivity, data.getData() + "");
                            quickCallJs("taskResult", null, type1, "true");
                            if (SHARE_MEDIA.WEIXIN == platform) {
                                ShuaApplication.is_bind_wechat = true;
                            }
                        } else {
                            ToastUtil.show(mActivity, data.getMessage() + "");
                        }
                    }
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                    LoadDialogManager.getInstance().dismiss();
                    ToastUtil.showToast(mActivity, "绑定失败,请重试");
                }
            });
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            LoadDialogManager.getInstance().dismiss();
            Toast.makeText(mActivity, t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            LoadDialogManager.getInstance().dismiss();
            Toast.makeText(mActivity, "绑定取消了", Toast.LENGTH_LONG).show();
        }
    };


    public static H5Fragment2 newInstance(String url) {
        Bundle args = new Bundle();
        args.putString("url", url);
        H5Fragment2 fragment = new H5Fragment2();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initView(View root) {
        webview = root.findViewById(R.id.webview);
        mTvTitle = root.findViewById(R.id.tv_title);
        mTvTitle.setText("任务");
        disposable = RxBus.getInstance().toObservable(BindWX.class)
                .subscribe(eventTwo -> quickCallJs("taskResult", null, AdvertConstants.REWARD_TYPE_BIND, "true"));
    }

    @Override
    protected void initData() {
        initTTSDKConfig();
        String userId = Store.getInstance().getuserId();
        if (TextUtils.isEmpty(userId)) {
            userId = Util.getDeviceId(ShuaApplication.getContext());
        }
        ad = new Ad("LStcTsHrCoiyj7ejw5KnvpQyq9b", 361360 + "", userId, "");
        ad.init(mActivity, null, Ad.AD_URL_NEW, new AdCallBack() {

            @Override
            public void onReceiveAd() {
                Log.d("========", "onReceiveAd");
            }

            @Override
            public void onFailedToReceiveAd(int errorCode, String errorMsg) {
                Log.d("========", "onFailedToReceiveAd  Message=" + errorMsg);
            }

            @Override
            public void onActivityClose() {
                Log.d("========", "onActivityClose");
            }

            @Override
            public void onActivityShow() {
                Log.d("========", "onActivityShow");
            }

            @Override
            public void onRewardClose() {
                Log.d("========", "onRewardClose");
            }

            @Override
            public void onRewardShow() {
                Log.d("========", "onRewardShow");
            }

            @Override
            public void onPrizeClose() {
                Log.d("========", "onPrizeClose");
            }

            @Override
            public void onPrizeShow() {
                Log.d("========", "onPrizeShow");
            }
        });
//        if (ad != null) {
////                    ad.resetSlotId(slotId+"");
//            ad.loadAd(mActivity, false);
//        }
    }

//    private int count = 0;
//
//    @Override
//    public void onSupportVisible() {
//        super.onSupportVisible();
//        count = count + 1;
//        if(count == 2){
//            if (ad != null) {
//                ad.loadAd(mActivity, false);
//            }
//        }
//    }

    private void initTTSDKConfig() {
        //step2:创建TTAdNative对象，createAdNative(Context context) banner广告context需要传入Activity对象
        mTTAdNative = TTAdManagerHolder.get().createAdNative(getContext());
        //step3:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
//        TTAdManagerHolder.get().requestPermissionIfNecessary(this);
    }

    /**
     * 推啊插屏
     */
    public void showAd() {
        if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose()){
            return;
        }
        if(ShuaApplication.isTuiaTaskOpen()){
            if (ad != null) {
                ad.loadAd(mActivity, false);
            }
        }else{
            loadExpressAd("945645219", 270, 270);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() == null) {
            return;
        }
        url = getArguments().getString("url");
        if (TextUtils.isEmpty(url)) {
            return;
        }
        initWebView();
        webview.loadUrl(url);
    }

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebView() {

        WebSettings ws = webview.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 不缩放
//        webView.setInitialScale(100);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // 排版适应屏幕
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        // WebView是否新窗口打开(加了后可能打不开网页)
//        ws.setSupportMultipleWindows(true);

        // webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用)*/
        ws.setTextZoom(100);

//        mWebChromeClient = new MyWebChromeClient(this);
//        webview.setWebChromeClient(mWebChromeClient);
        // 与js交互
        webview.addJavascriptInterface(new TaskJSInterface(), "android");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        // 1.设置WebChromeClient，重写文件上传回调
        webview.setWebChromeClient(new WebChromeClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

    }

    @Override
    protected void initViewModel() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_h5;
    }

    //============================== App to H5 ==============================

    //"type": String, // "PUNCH":会员签到, "TASK" :限次激励, "SHARE_VIDEO"：分享任务,
    // "FIRST_GET" :首次观看,  "LIKE" :点赞视频, "BIND_WECHAT"：绑定微信, "OPEN_NOTIFICATION"：开启推送, "TIME_LIMIT"：限时登录, "APPRAISE"：长豆评价
    //result: true 成功 false：失败
    private void rewardedAdvertResult(String result) {
        quickCallJs("rewardedAdvertResult", null, mAdvertType, result);
    }

    private void popViewCallbackEvent(String popType) {
        quickCallJs("PopViewCallbackEvent", null, popType);
    }

    //'modName': 'theTaskMod'
    public void scrollToModle(String modName){
        ScrollModle scrollModle = new ScrollModle();
        scrollModle.setModName(modName);
        String json = ParseJsonUtils.toJson(scrollModle);
        quickCallJs("scrollToModle", null, json);
    }


    private void quickCallJs(String method, ValueCallback<String> callback, String... params) {
        StringBuilder sb = new StringBuilder();
        sb.append("javascript:" + method);
        if (params == null || params.length == 0) {
            sb.append("()");
        } else {
            sb.append("(").append(WebUtils.concat(params)).append(")");
        }
        callJs(sb.toString(), callback);
    }

    private void callJs(String js, final ValueCallback<String> callback) {
        if (webview != null) {
            webview.evaluateJavascript(js, null);
        }
    }

    //============================== App to H5 ==============================

    public void reload() {
        if (webview != null) {
//            webview.reload();
            quickCallJs("refreshData", null);
        }
    }

    private boolean ToLogin() {
        if (!Store.getInstance().isLogin()) {
            Intent intent = new Intent(mActivity, LoginActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (toNotify) {
            quickCallJs("taskResult", null, AdvertConstants.REWARD_TYPE_NOTIFICATION, NotificationUtil.isNotifyEnabled(mActivity) + "");
            toNotify = false;
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        if (webview != null && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onBackPressedSupport();
    }

    public boolean isConsume(int keyCode, KeyEvent event) {
        return ad.onKeyBack(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.destroy();
        }
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
        if (ad != null) {
            ad.destroy();
        }
        if (mTTAd != null) {
            mTTAd.destroy();
        }
        LoadDialogManager.getInstance().dismiss();
    }

    private RewardPopupFragment mPopupFragment;

    public boolean isShowPopup() {
        if (mPopupFragment == null) {
            return false;
        }
        return mPopupFragment.isVisible();
    }

    private void hidePopupFragment() {
        if (mPopupFragment == null) return;
        hideFragment(mPopupFragment);
        mPopupFragment = null;
    }

    private class TaskJSInterface {


        @JavascriptInterface
        public String getToken() {
            return ShuaApplication.token;
        }

        @JavascriptInterface
        public String getDeviceId() {
            return Util.getDeviceId(ShuaApplication.getContext());
        }

        @JavascriptInterface
        public String getBlackBox() {
            return ShuaApplication.blackbox;
        }

        @JavascriptInterface
        public String getAccessToken() {
            return ShuaApplication.accessToken;
        }

        @JavascriptInterface
        public String getChannel() {
            return ShuaApplication.channel;
        }

        //打开微信
        @JavascriptInterface
        public void openWeChat() {
            if (UMShareAPI.get(mActivity).isInstall(mActivity, SHARE_MEDIA.WEIXIN)) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName cn = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.setComponent(cn);
                startActivity(intent);
            } else {
                Toast.makeText(mActivity, "您没有安装微信，请先安装", Toast.LENGTH_SHORT).show();
            }
        }

        //奖池活动点击
        @JavascriptInterface
        public void prizePoolEvent() {
//            Store.getInstance().setH5Guafeng(false);
        }

        @JavascriptInterface
        public void openHome() {
            if (getContext() instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) getContext();
                mainActivity.openHome();
            }
        }

        @JavascriptInterface
        public void openHot() {
            if (getContext() instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) getContext();
                mainActivity.openHot();
            }
        }

        @JavascriptInterface
        public void openGame() {
            if (!ToLogin()) {
                /**
                 * userId : 用户uid
                 * advertType: 0（默认值）显示全部数据  1.手游  2.棋牌游戏
                 */
                DyAdApi.getDyAdApi().jumpAdList(mActivity, Store.getInstance().getuserId(), 0);
            }
        }

        //分享至第三方平台
        @JavascriptInterface
        public void share() {
            if (getContext() instanceof MainActivity) {
                MainActivity mainActivity = (MainActivity) getContext();
                mainActivity.openHome();
                EventBus.getDefault().post(new ToShare());
            }
        }

        //去应用市场评价
        @JavascriptInterface
        public void comment() {
            MarketTools.getTools().startMarket(mActivity);//打开应用市场，打开当前安装应用的手机应用市场

        }

        //获取通知栏权限是否已经开启
        @JavascriptInterface
        public void isNotifyEnabled() {
            webview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    quickCallJs("taskResult", null, AdvertConstants.REWARD_TYPE_NOTIFICATION, NotificationUtil.isNotifyEnabled(mActivity) + "");
                }
            }, 100);
        }

        //去开启通知开启
        @JavascriptInterface
        public void toNotify() {
            toNotify = true;
            ToNotification.open(mActivity);

        }

        //绑定微信
        @JavascriptInterface
        public void toBingWX() {
            mActivity.runOnUiThread(() -> {
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                UMShareAPI.get(mActivity).setShareConfig(config);
                if (UMShareAPI.get(mActivity).isInstall(mActivity, SHARE_MEDIA.WEIXIN)) {
                    UMShareAPI.get(mActivity).getPlatformInfo(mActivity, SHARE_MEDIA.WEIXIN, authListener);
                } else {
                    Toast.makeText(mActivity, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
                }
            });
        }

        //绑定QQ
        @JavascriptInterface
        public void toBingQQ() {
            mActivity.runOnUiThread(() -> {
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                UMShareAPI.get(mActivity).setShareConfig(config);
                if (UMShareAPI.get(mActivity).isInstall(mActivity, SHARE_MEDIA.QQ)) {
                    UMShareAPI.get(mActivity).getPlatformInfo(mActivity, SHARE_MEDIA.QQ, authListener);
                } else {
                    Toast.makeText(mActivity, "您的设备未安装QQ客户端", Toast.LENGTH_SHORT).show();
                }
            });
        }

        //绑定weibo
        @JavascriptInterface
        public void toBingWeibo() {
            mActivity.runOnUiThread(() -> {
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                UMShareAPI.get(mActivity).setShareConfig(config);
                if (UMShareAPI.get(mActivity).isInstall(mActivity, SHARE_MEDIA.SINA)) {
                    UMShareAPI.get(mActivity).getPlatformInfo(mActivity, SHARE_MEDIA.SINA, authListener);
                } else {
                    Toast.makeText(mActivity, "您的设备未安装微博客户端", Toast.LENGTH_SHORT).show();
                }
            });
        }

        private boolean isRewarding = false;

        //激励视频
        //"type": String, // "PUNCH":会员签到, "TASK" :限次激励, "SHARE_VIDEO"：分享任务,
        // "FIRST_GET" :首次观看,  "LIKE" :点赞视频, "BIND_WECHAT"：绑定微信, "OPEN_NOTIFICATION"：开启推送, "TIME_LIMIT"：限时登录, "APPRAISE"：长豆评价
        @JavascriptInterface
        public void rewardedAdvert(String type) {
            callRewardedAdvert(type, "");
        }

        @JavascriptInterface
        public void rewardedAdvertEvent(String type, String reportId) {
            callRewardedAdvert(type, reportId);
        }

        private void callRewardedAdvert(String type, String reportId){
            mActivity.runOnUiThread(() -> {
                if (isRewarding) {
                    return;
                }
                isRewarding = true;
                if (webview != null) {
                    webview.postDelayed(() -> isRewarding = false, 2000);
                } else {
                    isRewarding = false;
                }
                if (!ToLogin()) {
                    mAdvertType = type;
                    RewardAdvertManager.getInstance().showAdvert(mActivity, mAdvertType, reportId, new OnRewardListener() {
                        @Override
                        public void onAdClose() {
                            rewardedAdvertResult("true");
                        }

                        @Override
                        public void onAdClick() {

                        }

                        @Override
                        public void onVideoComplete() {

                        }

                        @Override
                        public void onVideoError() {
                            rewardedAdvertResult("false");
                        }
                    });
                }
            });
        }

        //to提现
        @JavascriptInterface
        public void toWallet() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw").putExtra("title", "我的钱包"), WITHDRAW);
                //任务：945109760； 签到：945109757
//            loadAd("945109757", "任务", rewardAmount);

            }
        }

        //跳转到h5的次级界面
        @JavascriptInterface
        public void redirectEvent(String uri, String title) {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + uri).putExtra("title", title), CommonConstants.MAIN);
            }
        }

        @JavascriptInterface
        public void loadWebEvent(String url, String title) {
            startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", url).putExtra("title", title), CommonConstants.MAIN);
        }

        //to兑换/金豆
        @JavascriptInterface
        public void toWing() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "wallet?tabs=1").putExtra("title", "我的金豆"), CommonConstants.MAIN);
            }
        }

        //to邀请好友/师徒
        @JavascriptInterface
        public void toFriend() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true), REFRESH);
            }

        }

        //to补填邀请码
        @JavascriptInterface
        public void toCode() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "invite").putExtra("title", "补填邀请码").putExtra("Refresh", true), REFRESH);
            }

        }

        //to身份信息完善
        @JavascriptInterface
        public void toPersonal() {
            if (!ToLogin()) {
                startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "setInfo").putExtra("title", "完善信息").putExtra("Refresh", true), REFRESH);
            }
        }

        //是否不再提醒
        @JavascriptInterface
        public boolean isCalendarReminded() {
            return CalendarManager.getInstance().isCalendarReminded();
        }

        @JavascriptInterface
        public void setCalendarReminded() {
            CalendarManager.getInstance().setCalendarReminded(true);
        }

        @JavascriptInterface
        public void reportAdvertAction(int pageId, String action, String note) {
            mActivity.runOnUiThread(() -> TrackManager.getInstance().reportAdvertAction(pageId, action, note));
        }

        // 开启提醒规则
        @JavascriptInterface
        public void startCalendarRemind() {
            CalendarManager.getInstance().startCalendarRemind(getActivity());
        }

        @JavascriptInterface
        public String getAppVersion() {
            return getVersionName();
        }

        @JavascriptInterface
        public String getSystemModel() {
            return android.os.Build.MODEL;
        }

        @JavascriptInterface
        public String getApiVersion() {
            return CommitUtils.API_VERSION;
        }

        /**
         * 跳转到指定界面
         *
         * @param data json格式，{"type": "home"}
         *             "home":视频首页；"task":任务；"friend":邀请好友；"xdraw":提现；"hot_share";热点视频分享；"turntable":大转盘；"jiangchi":奖池
         */
        @JavascriptInterface
        public void jumpEvent(String data) {
            mActivity.runOnUiThread(() -> {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JumpJson result = ParseJsonUtils.parseData(data + "", JumpJson.class);
                if (result == null) {
                    return;
                }
                EventBus.getDefault().post(result);
            });
        }


        @JavascriptInterface
        public void login() {
            Intent intent = new Intent(mActivity, LoginActivity.class);
            startActivity(intent);
        }

        @JavascriptInterface
        public void logout() {
            Store.getInstance().logoutFromH5Page(mActivity);
        }

        private boolean isPopShowing;

        //关闭回调：PopNationDayCallbackEvent，传jsonString
        //type: startNow：“立即开始”；dayReward：1号到7号的奖励弹窗；giftReward：8号的礼品奖励
        @JavascriptInterface
        public void PopNationDayEvent(String jsonString) {
            mActivity.runOnUiThread(() -> {
                NationalBean result = ParseJsonUtils.parseData(jsonString + "", NationalBean.class);
                //TODO: 1、show pop; 2、call PopNationDayCallbackEvent after pop close

            });
        }

        //检查更新
        @JavascriptInterface
        public void checkUpgrade() {
            mActivity.runOnUiThread(Beta::checkUpgrade);
        }

        @JavascriptInterface
        public void PopViewEvent(String jsonString) {
            mActivity.runOnUiThread(() -> {
                if (isPopShowing) {
                    return;
                }
                isPopShowing = true;
                if (webview != null) {
                    webview.postDelayed(() -> isPopShowing = false, 1500);
                } else {
                    isPopShowing = false;
                }
                hidePopupFragment();
                Giftjson result = ParseJsonUtils.parseData(jsonString + "", Giftjson.class);
                mPopupFragment = RewardPopupFragment.newInstance(result.getTitle(), result.getSubTitle(), result.getValue(), result.getUiType() + "", result.getPopType());
                mPopupFragment.setPopupListener(new OnPopupListener() {
                    @Override
                    public void onNext() {
                        hidePopupFragment();
                        popViewCallbackEvent(result.getPopType());
                    }

                    @Override
                    public void onClose() {
                        hidePopupFragment();
                    }
                });
                showFragment(R.id.fl_popup, mPopupFragment);
                NativeAdvertManager.getInstance().loadExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_ENCOURAGE, new InteractionAdListener() {
                    @Override
                    public void onRenderSuccess(View view) {
                        webview.postDelayed(() -> {
                            if (mPopupFragment != null) {
                                mPopupFragment.addAdvertView(view);
                            }
                        }, 400);
                    }

                    @Override
                    public void onError() {
                        webview.postDelayed(() -> {
                            if (mPopupFragment != null) {
                                mPopupFragment.loadAdvertFail();
                            }
                        }, 400);
                    }
                });
            });
        }
    }

    // 2.回调方法触发本地选择文件
    private void openImageChooserActivity() {
//        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("file/*");//文件上传
//        i.setType("*/*");//文件上传
//        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");//图片上传

        try {
            startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void jumpToFriend() {
        if (!ToLogin()) {
            startActivityForResult(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true), REFRESH);
        }
    }

    private void dealWithdrawResult(String taskType) {
        if (TextUtils.isEmpty(taskType)) {
            scrollToModle("theTaskMod");
            return;
        }
        if ("task".equals(taskType)) {
            scrollToModle("theTaskMod");
            return;
        }
        if ("friend".equals(taskType)) {
            jumpToFriend();
        }else if ("home".equals(taskType)) {
            ((MainActivity) mActivity).openHome();
        }else if ("game".equals(taskType)) {
            DyAdApi.getDyAdApi().jumpAdList(mActivity, Store.getInstance().getuserId(), 0);;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonConstants.MAIN) {
            if (resultCode == RESULT_OK) {
                ((MainActivity) mActivity).openHome();
            }
        } else if (requestCode == WITHDRAW) {
            if (resultCode == RESULT_OK) {
                try {
                    String taskType = data.getStringExtra("taskType");
                    dealWithdrawResult(taskType);
                } catch (Exception e) {
                    ((MainActivity) mActivity).openHome();
                }
            }
        } else if (requestCode == REFRESH) {
            if (resultCode == RESULT_OK) {
                reload();
            }
            //3.选择图片后处理
        } else if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            // Uri result = (((data == null) || (resultCode != RESULT_OK)) ? null : data.getData());
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else {
            //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
            //WebView对象，在用户取消文件选择器的情况下，需给onReceiveValue传null返回值
            //否则WebView在未收到返回值的情况下，无法进行任何操作，文件选择器会失效
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            } else if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
        }
    }

    // 4. 选择内容回调到Html页面
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }


    //获取当前版本号
    private String getVersionName() {
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = mActivity.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0";
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (ad != null) {
            ad.resetAdSize(newConfig.orientation);
        }
    }

    private void loadExpressAd(String codeId, int expressViewWidth, int expressViewHeight) {
        if(mTTAdNative == null){
           initTTSDKConfig();
        }
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId) //广告位id
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
                .build();
        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
//                TToast.show(InteractionExpressActivity.this, "load error : " + code + ", " + message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                    return;
                }
                mTTAd = ads.get(0);
                bindAdListener(mTTAd);

                showAdvert();
//                startTime = System.currentTimeMillis();
//                TToast.show(mContext, "load success !");
            }
        });
    }

    private void showAdvert() {
        if (mTTAd != null) {
            mTTAd.render();
        }
    }


    private void bindAdListener(TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
            @Override
            public void onAdDismiss() {
//                TToast.show(mContext, "广告关闭");
            }

            @Override
            public void onAdClicked(View view, int type) {
//                TToast.show(mContext, "广告被点击");
            }

            @Override
            public void onAdShow(View view, int type) {
//                TToast.show(mContext, "广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
//                Log.e("ExpressView", "render fail:" + (System.currentTimeMillis() - startTime));
//                TToast.show(mContext, msg + " code:" + code);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
//                Log.e("ExpressView", "render suc:" + (System.currentTimeMillis() - startTime));
                //返回view的宽高 单位 dp
//                TToast.show(mContext, "渲染成功");
                mTTAd.showInteractionExpressAd(mActivity);

            }
        });
//        bindDislike(ad, false);
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
//                TToast.show(InteractionExpressActivity.this, "点击开始下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
//                if (!mHasShowDownloadActive) {
//                    mHasShowDownloadActive = true;
//                    TToast.show(InteractionExpressActivity.this, "下载中，点击暂停", Toast.LENGTH_LONG);
//                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "下载暂停，点击继续", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "下载失败，点击重新下载", Toast.LENGTH_LONG);
            }

            @Override
            public void onInstalled(String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "安装完成，点击图片打开", Toast.LENGTH_LONG);
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                TToast.show(InteractionExpressActivity.this, "点击安装", Toast.LENGTH_LONG);
            }
        });
    }


}